package net.zkbc.helloworld.view;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.view.document.AbstractXlsxView;

import net.zkbc.helloworld.entity.User;
import net.zkbc.shared.SharedVars;
import net.zkbc.shared.util.ExcelViewUtils;

@Component(UserXlsxView.INSTNAME)
public class UserXlsxView extends AbstractXlsxView {
	public static final String INSTNAME = "userXlsxView";

	@Autowired
	private SharedVars appVars;

	@Override
	protected XSSFWorkbook createWorkbook(Map<String, Object> model, HttpServletRequest request) {
		try {
			return new XSSFWorkbook(new ByteArrayInputStream(FileCopyUtils.copyToByteArray(
					new File(ResourceUtils.getFile(appVars.xlsxTemplateExportRoot), "helloworld/user.xlsx"))));
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	@Override
	protected void buildExcelDocument(Map<String, Object> model, final Workbook workbook, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		setContentDisposition(response, "用户.xlsx");

		ExcelViewUtils.fill(workbook, model, new ExcelViewUtils.FillCellCallback<User>() {
			@Override
			public void fill(Cell cell, String propName, User dataRow) {
				switch (propName) {
				case "id":
					cell.setCellValue(dataRow.getId());
					break;
				case "loginName":
					cell.setCellValue(dataRow.getLoginName());
					break;
				default:
					break;
				}
			}
		});
	}

	public void setContentDisposition(HttpServletResponse response, String filename)
			throws UnsupportedEncodingException {
		String encodedFilename = URLEncoder.encode(filename, "UTF-8");
		response.setHeader("Content-Disposition",
				"attachment; filename=\"" + encodedFilename + "\"; filename*=utf-8''" + encodedFilename);
	}

}
